<template>
  <div>
    <tdt-map
      ref="tdtMap"
      style="width: 100%; height: 1500px"
      :center="state.center"
      :zoom="state.zoom"
      :loadConfig="loadConfig"
      @init="mapInit"
    >
      <!-- Marker 聚合 -->
      <tdt-marker-clusterer :markers="markers" :styles="styles" />

      <!-- 高亮全部省份 -->
      <tdt-polygon
        v-for="(p, i) in provincePolygons"
        :key="i"
        :path="p.path"
        :strokeColor="p.strokeColor || '#ff0000'"
        :fillColor="p.fillColor || 'rgba(255,0,0,0.2)'"
        :strokeWeight="p.strokeWeight || 2"
      />

      <!-- 中心点 Marker -->
      <tdt-marker
        :position="state.center"
        :draggable="false"
        icon="https://soullyoko.github.io/vue-tianditu/marker_red.png"
      />

      <!-- 信息窗 -->
      <tdt-infowindow v-model:target="target" :content="content" />
    </tdt-map>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import 'vue-tianditu/lib/style.css'
import chinaGeoJson from '@/assets/chinas.json' // 你的中国省份 GeoJSON 文件路径
import pointInPolygon from 'point-in-polygon'
const loadConfig = { v: '4.0', tk: '8362ba89b7bfb71c70cac2ef0390132a' }

const state = reactive({
  center: [116.404, 39.915],
  zoom: 6,
})

const target = ref(null)
const content = ref('')
const map = ref(null)

// 自定义聚合样式
const styles = ref([
  {
    url: 'https://api.tianditu.gov.cn/img/map/markers/b1.png',
    size: [32, 32],
    offset: [-16, -32],
    textColor: '#fff',
    textSize: 12,
    range: [0, 50],
  },
  {
    url: 'https://api.tianditu.gov.cn/img/map/markers/b2.png',
    size: [48, 48],
    offset: [-24, -48],
    textColor: '#FF0000',
    textSize: 14,
    range: [50, 200],
  },
  {
    url: 'https://api.tianditu.gov.cn/img/map/markers/b3.png',
    size: [64, 64],
    offset: [-32, -64],
    textColor: '#000',
    textSize: 16,
    range: [200, 10000],
  },
])

// 生成 10,000 个点位数据（北京附近）
const defaultIcon = 'https://soullyoko.github.io/vue-tianditu/marker_red.png'
const activeIcon = 'https://soullyoko.github.io/vue-tianditu/marker_blue.png'

// 判断点是否在中国范围内
function isPointInChina(lng, lat) {
  if (!chinaGeoJson || !chinaGeoJson.features) return false

  for (const province of chinaGeoJson.features) {
    const { type, coordinates } = province.geometry

    if (type === 'Polygon') {
      for (const ring of coordinates) {
        if (pointInPolygon([lng, lat], ring)) {
          return true
        }
      }
    } else if (type === 'MultiPolygon') {
      for (const polygon of coordinates) {
        for (const ring of polygon) {
          if (pointInPolygon([lng, lat], ring)) {
            return true
          }
        }
      }
    }
  }
  return false
}
// 生成中国范围内随机点
function generateChinaPoints(count = 10000) {
  const points = []
  while (points.length < count) {
    // 中国大陆经纬度大致范围
    const lng = 73 + Math.random() * (135 - 73)
    const lat = 18 + Math.random() * (54 - 18)

    if (isPointInChina(lng, lat)) {
      const id = points.length
      points.push({
        position: [lng, lat],
        icon: defaultIcon,
        extData: { id },
        events: {
          click(e) {
            e.target.setIcon(activeIcon)
            content.value = `你点击了点位：${id}`
            target.value = e.target
          },
        },
      })
    }
  }
  return points
}
const markers = ref(generateChinaPoints(10000))
// 高亮全部省份的多边形数组
const provincePolygons = ref([])

// 初始化地图，加载全部省份
function mapInit(m) {
  map.value = m
  drawAllProvinces()
}

// 将 GeoJSON 转成多边形 path，支持 Polygon 和 MultiPolygon
function drawAllProvinces() {
  if (!chinaGeoJson || !chinaGeoJson.features) return

  const polygons = []

  chinaGeoJson.features.forEach((province) => {
    const { type, coordinates } = province.geometry

    if (type === 'Polygon') {
      // Polygon 结构，coordinates 是数组套数组
      coordinates.forEach((ring) => {
        polygons.push({
          path: ring,
          strokeColor: '#ff0000',
          fillColor: 'rgba(255,0,0,0.2)',
          strokeWeight: 2,
        })
      })
    } else if (type === 'MultiPolygon') {
      // MultiPolygon 结构，coordinates 是三层数组
      coordinates.forEach((polygon) => {
        polygon.forEach((ring) => {
          polygons.push({
            path: ring,
            strokeColor: '#ff0000',
            fillColor: 'rgba(255,0,0,0.2)',
            strokeWeight: 2,
          })
        })
      })
    }
  })

  provincePolygons.value = polygons
}
</script>
